import React, { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom'
import { UserOutlined } from '@ant-design/icons';
import { Layout, Menu, Button, Avatar, Modal } from 'antd'
import { setStore, getStore, removeStore } from '@/utils/commons'
import Login from '@/components/login'
import Register from '@/components/register'
import Forget from '@/components/forget'
import API from '@/api/api'
import logoImg from '../../assets/img/logo.png'
import hotImg from '../../assets/img/hot.png'
import './index.scss'

const { confirm } = Modal;
const { Header } = Layout;
const { SubMenu } = Menu;

function HeaderBox(props) {
    const [navIndex, setNavIndex] = useState()
    const [user, setUser] = useState(0)
    const [phoneAreaList, setPhoneAreaList] = useState({})
    const [loginStatus, setLoginStatus] = useState(false)
    const [registerStatus, setRegisterStatus] = useState(false)
    const [forgetStatus, setForgetStatus] = useState(false)
    const navList = [
        { name: '首页', url: '/home' },
        { name: '云算力', url: '/power', icon: hotImg },
        { name: '云矿机', url: '/miner' },
        { name: '公告', url: '/notice' },
        { name: '合作伙伴', url: 'partner' },
        { name: '会员中心', url: '/dashboard' },
    ]
    let history = useHistory()

    useEffect(() => {
        let pathname = window.location.pathname
        navList.map((value, index) => {
            if (pathname === value.url) {
                setNavIndex(index.toString())
            }
        })
        getErrorCode()
        getRegister()
        getUserInfo()
    }, [])


    const getErrorCode = async () => {
        let edition = 'km0508'  // 错误码版本号
        let errorCodeEdition = getStore("errorCodeEdition");
        if (!errorCodeEdition || errorCodeEdition !== edition) {
            let errorCodeRes = await API.getErrorCode();
            if (errorCodeRes) {
                setStore("errorCode", errorCodeRes);
                setStore("errorCodeEdition", edition);
            }
        }
    }

    const getRegister = async () => {
        if (getStore('phoneAreaList')) {
            let list = JSON.parse(getStore('phoneAreaList'))
            setPhoneAreaList(list)
        } else {
            let res = await API.getRegister();
            if (res) {
                setPhoneAreaList(res)
                setStore('phoneAreaList', JSON.stringify(res))
            }
        }
    }

    const getUserInfo = () => {
        let user = getStore('userInfo')
        if (user) {
            setUser(JSON.parse(user))
        }
    }

    const logout = () => {
        confirm({
            title: '是否确定退出登录？',
            okText: '确定退出',
            cancelText: '取消',
            onOk() {
                removeStore('token')
                removeStore('userInfo')
                history.push('/')
            },
            onCancel() { console.log('Cancel'); },
        });

    }

    const toLogin = () => {
        setLoginStatus(true)
        setRegisterStatus(false)
        setForgetStatus(false)
    }

    const toRegister = () => {
        setLoginStatus(false)
        setRegisterStatus(true)
        setForgetStatus(false)
    }

    const toForget = () => {
        setLoginStatus(false)
        setRegisterStatus(false)
        setForgetStatus(true)
    }

    const cancelModal = () => {
        setForgetStatus(false)
        setLoginStatus(false)
        setRegisterStatus(false)
    }

    const scrollToAnchor = (anchorName) => {
        if (anchorName.includes('/')) {
            window.location.href = anchorName;
        } else {
            let pathname = window.location.pathname
            if (pathname !== '/home') {
                window.location.href = '/home'
            }
            let anchorElement = document.getElementById(anchorName);
            if (anchorElement) { anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' }); }
        }
    }

    const menuItem = (value, index) => {
        return index < 5 ?
            <Menu.Item key={index} onClick={() => scrollToAnchor(value.url)}>
                {value.name}
                {value.icon && <img className="header-hot" src={value.icon} alt='hot' />}
            </Menu.Item> : null
    }

    return (
        <Header className="header">
            <div className="main">
                <img className="header-logo" src={logoImg} alt='logo' onClick={() => history.push('/')} />
                <div className="header-right">
                    <Menu mode="horizontal" selectedKeys={[navIndex]}>
                        {
                            navList.map((value, index) => {
                                return menuItem(value, index)
                            })
                        }
                        {!user ? null : <SubMenu key={5} icon={<UserOutlined />} title="会员中心" onTitleClick={() => scrollToAnchor('/dashboard')}>
                            <Menu.Item key="logout"><a onClick={logout}>退出登录</a></Menu.Item>
                        </SubMenu>}
                    </Menu>

                    {user ? null : <Button className="header-register" type="primary" onClick={toRegister}>注册</Button>}
                    {user ? null : <Button onClick={toLogin}>登录</Button>}
                </div>
            </div>
            <Login status={loginStatus} phoneAreaList={phoneAreaList} close={cancelModal} toRegister={toRegister} toForget={toForget} />
            <Register status={registerStatus} phoneAreaList={phoneAreaList} close={cancelModal} toLogin={toLogin} />
            <Forget status={forgetStatus} phoneAreaList={phoneAreaList} close={cancelModal} toLogin={toLogin} toRegister={toRegister} />
        </Header >
    )
}

export default HeaderBox